# Copyright 2008 Thomas Quemard
#
# Grabova is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 3.0, or (at your option)
# any later version.
#
# Grabova is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.

import httplib
import os
import tempfile
import urllib2

class Client:
    name = ""
    support_web_torrents = False

    def download_torrent_to_temp_file(self, torrent_url):
        req = urllib2.Request(torrent_url)
        opener = urllib2.build_opener()
        f = opener.open(req)
        if f != None:
            tmp_file_path = tempfile.mktemp()
            tmp = open(tmp_file_path, "w+")
            if tmp != None:
                tmp.write(f.read())
                tmp.close()
            f.close()
        return tmp_file_path

    def run_client(self, name, arguments):
        pid = os.spawnvp(os.P_NOWAIT, name, arguments)
        return pid


class Null (Client):
    def __init__(self):
        self.name = "NullClient"
        self.support_web_torrents = True

    def run(self, torrent_title, torrent_url):
        print "  [I am <grabova.client.NullClient> and I'm NOT downloading <" + torrent_title + "> <" + torrent_url + ">]"
        return 0


class Azureus (Client):
    def __init__(self):
        self.name = "Azureus"
        self.support_web_torrents = True

    def run(self, torrent_title, torrent_url):
        return self.run_client("azureus", ["azureus", torrent_url]);


class BitTorrent (Client):
    def __init__(self):
        self.name = "BitTorrent"
        self.support_web_torrent = True

    def run(self, torrent_title, torrent_url):
        return self.run_client("btdownloadgui", ["btdownloadgui", torrent_url])


class Transmission (Client):
    def __init__(self):
        self.name = "Transmission"
        self.support_web_torrent = False

    def run(self, torrent_title, torrent_url):
        tmp_file = self.download_torrent_to_temp_file(torrent_url)
        return self.run_client("transmission", ["transmission", tmp_file])

